﻿using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using YWM.Localization;

namespace YWM.Dto
{
    public abstract class BaseDto : EmptyDto, IDataErrorInfo
    {
        #region 属性 
        /// <summary>
        /// 表当验证错误集合
        /// </summary>
        public Dictionary<string, string> DataErrors { get; set; } = new Dictionary<string, string>();

        /// <summary>
        /// 是否验证通过
        /// </summary>
        public bool IsValidated
        {
            get { return DataErrors.Count == 0; }
        }

        public string this[string columnName]
        {
            get
            {
                ValidationContext vc = new ValidationContext(this, null, null);
                vc.MemberName = columnName;
                List<ValidationResult> res = new List<ValidationResult>();
                bool result = Validator.TryValidateProperty(GetType().GetProperty(columnName).GetValue(this, null), vc, res);
                if (!result && res.Count > 0)
                {
                    string errorMessage = YApp.Resolve<ILocalizationManager>()[res[0].ErrorMessage];
                    AddDic(DataErrors, columnName, errorMessage);
                    return errorMessage;
                }
                RemoveDic(DataErrors, columnName);
                return null;
            }
        }

        private string _error;
        public string Error
        {
            get { return _error; }
            set { SetProperty(ref _error, value); }
        }
        #endregion

        #region 附属方法

        /// <summary>
        /// 移除字典
        /// </summary>
        /// <param name="dics"></param>
        /// <param name="dicKey"></param>
        private void RemoveDic(Dictionary<string, string> dics, string dicKey)
        {
            dics.Remove(dicKey);
        }

        /// <summary>
        /// 添加字典
        /// </summary>
        /// <param name="dics"></param>
        /// <param name="dicKey"></param>
        private void AddDic(Dictionary<string, string> dics, string dicKey, string dicValue)
        {
            if (!dics.ContainsKey(dicKey))
            {
                dics.Add(dicKey, dicValue);
            }
        }
        #endregion
    }
}
